package service;

import graph.DbEdgesImplFactory;
import graph.DirectedEdges;
import graph.EdgesBuilder;
import graph.EdgesConfig;
import graph.EdgesImplFactory;
import graph.PropertyManager;

import java.io.File;
import java.util.Set;

import mapreduce.IntegerFormat;
import mapreduce.Record;

import search.Lister;
import search.TwitterIndexer;
import util.Common;

public class Builder {
	public void build(File relationFile, File textFile){
		//1. build graph
		EdgesBuilder builder = new EdgesBuilder();
		EdgesConfig config = new EdgesConfig("user", "tweets", "favorite");
		DirectedEdges edges = builder.build(relationFile, Common.databaseDir(), config);
		
		//2. build index
		TwitterIndexer indexer = new TwitterIndexer(Common.indexDir());
		indexer.index(textFile, true);
		
		//3. build property manager
		String name = "favorite";
		PropertyManager propertyManager = Common.getPropertyManager(name);
		EdgesImplFactory implFactory = new DbEdgesImplFactory(Common.databaseDir().toString());
		DirectedEdges favoriteEdges = new DirectedEdges(implFactory,
				name);
		Set<Integer> tweetIds = favoriteEdges.getDesNodes();
		for (int tweetId : tweetIds) {
			int favoriteNum = favoriteEdges.getEdgesTo(tweetId).size();
			propertyManager.setProperty(tweetId, new Record.RecordData(
					favoriteNum, new IntegerFormat()));
		}
		propertyManager.sync();
		
		//4. list
		Lister lister = new Lister();
		lister.list(new File("../data/favorite.dat"));
	}
	
	public static void main(String[] args){
		int argIndex = 0;
		File relationFile = new File(args[argIndex++]);
		File textFile = new File(args[argIndex++]);
		Builder builder = new Builder();
		builder.build(relationFile, textFile);
	}
}
